package com.zhuqi.filter;

import cn.hutool.captcha.LineCaptcha;
import com.zhuqi.exception.CodeException;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author zhuqi
 * @version 1.0
 * @date 2021/3/26 8:51
 */
@Component
public class CodeFilter extends OncePerRequestFilter {
    /**
     * 执行过滤的方法 检验验证码
     *
     * @param request
     * @param response
     * @param filterChain
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 拿到请求的URI
        String uri = request.getRequestURI();
        String method = request.getMethod();
        // 判断是否为登录请求,如果是登录请求就进行验证码判断
        if (uri.equals("/dologin") && method.equals("post")) {
            // 获取验证码进行判空
            String code = request.getParameter("code");
            // 如果 请求带有 code 就往下执行
            if (StringUtils.hasText(code)) {
                // 从 session 中拿到code 进行对比,如果验证通过就放行
                LineCaptcha lineCaptcha = (LineCaptcha) request.getSession().getAttribute("code");
                boolean verify = lineCaptcha.verify(code);
                if (verify) {
                    filterChain.doFilter(request, response);
                    return;
                }
            }
            request.setAttribute("error",new CodeException());
            request.getRequestDispatcher("/codeError").forward(request,response);
            return;
        }
        // 其他请求放行 执行其他的过滤器
        filterChain.doFilter(request, response);
    }
}
